import React, { useEffect, useState, useCallback, useRef } from 'react'
import BScroll from 'better-scroll'
import { ScrollWrapper } from './styledScroll'
import { useDispatch } from 'react-redux'

export default function Scroll({
    children,
    id, 
    loadDataSaga, 
    list, 
    height,
    searchid,
    pullingUp
}) {
    const scroll = useRef(null)
    const firstLoad = useRef(true)
    let [currentPage, setCurrentPage] = useState(1)
    let [isPullUpLoad, setIsPullUpload] = useState(false)
    let dispatch = useDispatch()

    useEffect(() => {
        if (!firstLoad.current) {
            scroll.current.finishPullUp()
            // 在refresh()之前做，因为要回到上一次过拽的内容高度的位置
            scroll.current.scrollTo(0, scroll.current.maxScrollY + 80)
            scroll.current.refresh()
            setIsPullUpload(false)
        }
    }, [list, scroll])

    const pullingUpHandler = useCallback(
        async () => {
            firstLoad.current = false
            setCurrentPage(currentPage+1)
            setIsPullUpload(true)
    
          dispatch(loadDataSaga({"end":(currentPage+1) * 6,"id":searchid}))
        },
        [dispatch, currentPage, loadDataSaga,searchid],
    )

    useEffect(() => {
        if(pullingUp){
            scroll.current = new BScroll(`#${id}`, {
            pullUpLoad: true,
            click: true,
            mouseWheel: true
        })
        scroll.current.on('pullingUp', pullingUpHandler)
        }else{
            scroll.current = new BScroll(`#${id}`, {
                click: true,
                mouseWheel: true
            })
        }
        
        
    }, [scroll, pullingUpHandler, id])
    
    useEffect(() => {
        (async () => {
          // 异步函数可以直接await，会等待异步调用完成
            await dispatch(loadDataSaga({"end":6,"id":searchid}))
            scroll.current.refresh()
        })()
    }, [dispatch, scroll, loadDataSaga,searchid])
    return (
        <ScrollWrapper id={id} height = {height}>
            <div className="container">
            <>{children}</>
            <div className="pullup-tips">
                {
                !isPullUpLoad
                    ? (
                    <div className="before-trigger">
                        <span className="pullup-txt">Pull up and load more</span>
                    </div>
                    ) : (
                    <div className="after-trigger">
                        <span className="pullup-txt">Loading...</span>
                    </div>
                    )
                }
            </div>
            </div>
        </ScrollWrapper>
    )
}
